// Promise 封装 uni.request
import config from '@/utils/config'
const serverUrl = config.serverUrl
const METHOD = {
	GET: 'GET',
	POST: 'POST',
	PUT: 'PUT',
	DELETE: 'DELETE',
}

Promise.prototype.finally = function(callback) {
	const P = this.constructor
	return this.then(
		value => P.resolve(callback()).then(() => value),
		reason => P.resolve(callback()).then(() => {
			throw reason
		})
	)
}

function isAbsoluteURL(url) {
	return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url)
}

function combineURLs(url) {
	return serverUrl + url
}

function isEmpty(obj) {
	if (typeof obj == "undefined" || obj == null || obj == "") {
		return true;
	} else {
		return false;
	}
}

async function request(url, data, method, header, isShowToast, isJwt) {

	if (isShowToast) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	const promise = new Promise((resolve, reject) => {

		var hasJwt = data && data.hasOwnProperty('jwt')

		var jwt = ''
		if (hasJwt) {
			jwt = data.jwt
		} else {
			jwt = uni.getStorageSync('jwt') ? uni.getStorageSync('jwt') : ''
			// jwt="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjI2MDQzMSwidG9rZW4iOiJiYzBkMTVkMGJhOWJlZGMyYTFkYWU4NjI5NTQxZGQ5ZWVhNWM3NmMyIn0.IZfjpeiBEDIQn5KBX4dt7_ENOo5e3Kz6KbW5X1KtSKc"
		}

		// console.log('request jwt===',jwt)

		let _url = isAbsoluteURL(url) ? url : combineURLs(url);
		let _data = {};
		if (isJwt) {
			if (isEmpty(jwt)) {
				_data = data;
			} else {
				if (method == 'POST') {
					_url += '?jwt=' + jwt;
					_data = data;
				} else {
					_data = {
						jwt,
						...data
					}
				}
			}
		} else {
			_data = {
				...data
			}
		}
		console.log('request url === ', _url)
		console.log('request data === ', _data)
		uni.request({
			url: _url,
			data: _data,
			method,
			header,
			success: res => {
				if (isShowToast) {
					setTimeout(function() {
						uni.hideLoading()
					}, 500)
				}

				if (res.statusCode === 200) {
					if (res.data.errcode == 10006 || res.data.errcode == 2) {
						uni.showToast({
							title: "未登录或登录已过期，请先登录",
							icon: 'none',
							duration: 1000
						})
						uni.clearStorageSync();
						setTimeout(function() {
							uni.navigateTo({
								url: '/pages/login/login',
							})
						}, 1000)
					} else {
						resolve(res.data)
						console.log('request res === ', res.data)
					}

				} else {
					switch (res.statusCode) {
						case 400:
							// reject({
							//   msg: '请求错误'
							// })
							uni.showToast({
								title: '请求错误',
								icon: 'none',
								duration: 1000
							})
							break

						case 404:
							console.log('_url====', _url)
							uni.showToast({
								title: '接口不存在',
								icon: 'none',
								duration: 1000
							})
							break

						case 500:
							uni.showToast({
								title: '服务器错误',
								icon: 'none',
								duration: 1000
							})
							break

						default:
					}
				}
			},
			fail: error => {
				if (isShowToast) {
					setTimeout(function() {
						uni.hideLoading()
					}, 1000)
				}
				switch (error.errMsg) {
					case 'request:fail timeout':
						uni.showToast({
							title: '请求超时',
							icon: 'none',
							duration: 1000
						})
						break

					default:
						uni.showToast({
							title: '网络错误,或接口不存在',
							icon: 'none',
							duration: 1000
						})
						break
				}
			}
		})
	})

	return promise
}

function get(url, data, isShowToast = true, isJwt = true) {

	const header = {
		// 'content-type': 'application/json'
	}

	return request(url, data, METHOD.GET, header, isShowToast, isJwt)
}

function post(url, data, isShowToast = true, isJwt = true) {
	const header = {
		'content-type': 'application/x-www-form-urlencoded'
	}
	return request(url, data, METHOD.POST, header, isShowToast, isJwt)
}

function put(url, data, isShowToast = true, isJwt = true) {
	const header = {
		'content-type': 'application/json'
	}
	return request(url, data, METHOD.PUT, header, isShowToast, isJwt)
}

function _delete(url, data, isShowToast = true, isJwt = true) {
	const header = {
		'content-type': 'application/json'
	}
	return request(url, data, METHOD.DELETE, header, isShowToast, isJwt)
}


module.exports = {
	get,
	post,
	put,
	_delete
}
